package com.zzjcy.common.core.init;

import com.zzjcy.common.constants.Constants;
import com.zzjcy.common.domain.SystemFixedParam;
import com.zzjcy.common.mapper.user.SystemFixedParamMapper;
import com.zzjcy.common.util.Transformer;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by zhangzhi on 2017/8/8.
 */
/*@Lazy(false)
@EnableScheduling*/
public class ConfigUpdateScheduleJob implements SchedulingConfigurer {
	private static Logger logger = Logger.getLogger(ConfigUpdateScheduleJob.class);
	private final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

	@Autowired
	private CommonPropertyLoader commonPropertyLoader;

	@Autowired
	private SystemFixedParamMapper systemFixedParamMapper;

	private static String cron;

	public ConfigUpdateScheduleJob() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				if(systemFixedParamMapper != null){
					reloadConfig();
				}
			}
		}).start();
	}

	@Override
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		taskRegistrar.addTriggerTask(new Runnable() {
			@Override
			public void run() {
				logger.debug("这次运行时间为:" + dateFormat.format(new Date()));
				reloadConfig();
			}
		}, new Trigger() {
			@Override
			public Date nextExecutionTime(TriggerContext triggerContext) {
				// 任务触发，可修改任务的执行周期
				cron = CommonPropertyLoader.getContextProperty("configUpdateJob.cron");
				if(StringUtils.isEmpty(cron)){
					//cron = Constants.DEFAULT_CRONEXPRESSION;
				}
				CronTrigger trigger = new CronTrigger(cron);
				System.out.println("*********修改运行cron为******" +cron);
				Date nextExec = trigger.nextExecutionTime(triggerContext);
				return nextExec;
			}
		});
	}

	private void reloadConfig(){
		try {
			commonPropertyLoader.init();
			commonPropertyLoader.processStaticMap();
		}catch (Exception e){
			throw new RuntimeException("reload config.properties fail");
		}
		List<SystemFixedParam> sysList = systemFixedParamMapper.queryByModule(CommonPropertyLoader.getContextProperty("sys.module"));
		for(SystemFixedParam temp : sysList){
			String value = Transformer.parseEncValues(temp.getValue());
			System.setProperty(temp.getKey(),value.trim());
			//logger.debug("ConfigUpdateJobs设置****temp.getKey() =" + temp.getKey() + "***temp.getValue() =" + temp.getValue() + "***");
		}
	}
}
